const path = require('path')
const {sizeErr} = require('../lib/helper')
const MAX_SIZE = 1024 * 1024 * 1024 * 5
const fse = require('fs-extra')
const DIST_FOLDER_PATH = path.join(__dirname, '..', '..', 'uploadFiles')
const {success} = require('../lib/helper')

//目录不存在 新建一个
fse.pathExists(DIST_FOLDER_PATH).then(exist => {
    if (!exist) {
        fse.ensureDir(DIST_FOLDER_PATH)
    }
})

/***
 name 文件名
 type 文件类型
 size 文件大小
 filePath 文件路径
 **/
async function saveFile({name, type, size, filePath}, originPath) {
    if (size > MAX_SIZE) {
        await fse.remove(filePath)
        sizeErr()
    }

    //移动文件
    const fileName = Date.now() + '.' + name //防止重名
    const distFilePath = path.join(DIST_FOLDER_PATH, fileName) //目的地
    fse.move(filePath, distFilePath)

    //返回信息
    return success(originPath + '/' + fileName, '200')
}

module.exports = {
    saveFile
}